package org.gtugs.raffler.master;


import java.util.HashMap;

import org.alljoyn.bus.BusException;
import org.alljoyn.bus.Status;
import org.gtugs.raffler.pojo.Participant;
import org.gtugs.raffler.pojo.Prize;
import org.gtugs.raffler.pojo.Raffle;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.util.Log;

public class ServiceActivity extends Activity {
	/* Load the native alljoyn_java library. */
    static {
        System.loadLibrary("alljoyn_java");
    }
    
    public static final String TAG = "LocalRafflerMaster";
    
    /* The AllJoyn object that is our service. */
    private RaffleService mRaffleService;

    /* Handler used to make calls to AllJoyn methods. See onCreate(). */
    private Handler mBusHandler;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        
        
        
    }
    
    /**
     * Start the raffle after entering details and pressing create raffle
     */
    private void startRaffle() {
    	
    	/* Make all AllJoyn calls through a separate handler thread to prevent blocking the UI. */
        HandlerThread busThread = new HandlerThread("BusHandler");
        busThread.start();
        mBusHandler = new BusHandler(busThread.getLooper());

        /* Start our service. */
        mRaffleService = new RaffleService();
        mBusHandler.sendEmptyMessage(RaffleService.CONNECT);
        
        //TODO read actual values from GUI
        Raffle raffle = new Raffle("get title", 0);
        raffle.addPrize(new Prize("title prize 1", "description", 1, 10));
        raffle.addPrize(new Prize("title prize 2", "description", 1, 20));
        raffle.addPrize(new Prize("title prize 3", "description", 1, 30));
        
        /* Start the raffle */
        mRaffleService.createRaffle(raffle);
    }
    
    /**
     * Do the actual drawing and display the winners list
     * @throws BusException 
     */
    private void doDrawing() throws BusException {
    	HashMap<Prize, Participant> winners = mRaffleService.getRaffles().get(0).doDrawing();
    	
    	//TODO extract winners and display them in a ListView
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        
        /* Disconnect to prevent any resource leaks. */
        mBusHandler.sendEmptyMessage(RaffleService.DISCONNECT);        
    }
    
    private void logStatus(String msg, Status status) {
        String log = String.format("%s: %s", msg, status);
        if (status == Status.OK) {
            Log.i(TAG, log);
        } else {
            Log.e(TAG, log);
        }
    }
    
}
